package com.meow_woof.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meow_woof.dto.Result;
import com.meow_woof.entity.Shop;
import com.meow_woof.mapper.ShopMapper;
import com.meow_woof.service.IShopService;
import com.meow_woof.utils.CacheClient;
import com.meow_woof.utils.RedisData;
import com.meow_woof.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.meow_woof.utils.RedisConstants.*;

/**
 * 服务实现类
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheClient cacheClient;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);

    private Boolean tryLock(String key){
        return stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);

    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    public void saveShop2Redis(Long id,Long expireTime){
        Shop shop=getById(id);
        RedisData redisData=new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(redisData));
    }
    public Result queryById(Long id){
            //Shop shop=cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        //Shop shop=cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY,LOCK_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.SECONDS);
        //Shop shop=cacheClient.queryWithMutex(CACHE_SHOP_KEY,LOCK_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        /*Shop shop = cacheClient.queryWithPassThrough(
                CACHE_SHOP_KEY,
                id,
                Shop.class,
                this::getById,
                CACHE_SHOP_TTL,
                TimeUnit.MINUTES,
                BLOOM_SHOP_KEY   // 这里就是布隆过滤器的 key，比如 "bf:shop:id"
        );*/
        Shop shop = cacheClient.queryWithBloom(
                CACHE_SHOP_KEY,
                id,
                Shop.class,
                this::getById,
                CACHE_SHOP_TTL,
                TimeUnit.MINUTES
        );


        if(shop==null){
            return Result.fail("未查询到该店铺");

        }
        return Result.ok(shop);
    }

    //逻辑过期解决缓存击穿
//    public Result queryById(Long id) {
//        String key=CACHE_SHOP_KEY+id;
//        String shopCache = stringRedisTemplate.opsForValue().get(key);
//        if(StrUtil.isBlank(shopCache)){
//
//            return Result.fail("缓存中无该商铺");
//        }
//        RedisData redisData = JSONUtil.toBean(shopCache, RedisData.class);
//        LocalDateTime expireTime = redisData.getExpireTime();
//        JSONObject data = (JSONObject) redisData.getData();
//        Shop shop = JSONUtil.toBean(data, Shop.class);
//        if(expireTime.isAfter(LocalDateTime.now())){
//            return Result.ok(shop);
//        }
//
//
//        String lockKey=LOCK_SHOP_KEY+id;
//        Boolean isLock = tryLock(lockKey);
//        if(isLock){
//            if(expireTime.isAfter(LocalDateTime.now())){
//                return Result.ok(shop);
//            }
//            CACHE_REBUILD_EXECUTOR.submit(()->{
//                try {
//                    saveShop2Redis(id,20L);
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                } finally {
//                    unlock(lockKey);
//                }
//
//
//            });
//
//        }
//
//
//
//        return Result.ok(shop);
//    }
    //互斥锁解决缓存击穿
//    public Result queryById(Long id) {
//        String key=CACHE_SHOP_KEY+id;
//        String shopCache = stringRedisTemplate.opsForValue().get(key);
//        if(StrUtil.isNotBlank(shopCache)){
//            Shop shop = JSONUtil.toBean(shopCache, Shop.class);
//            return Result.ok(shop);
//
//        }
//        if(shopCache!=null){
//            return Result.fail("id不存在");
//        }
//
//        Shop shop;
//        String lockKey=LOCK_SHOP_KEY+id;
//        try {
//            boolean isLock=tryLock(lockKey);
//            if(!isLock){
//                Thread.sleep(50);
//                return queryById(id);
//
//
//            }
//            shop = getById(id);
//            if(shop==null){
//                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
//                return Result.fail("id不存在");
//            }
//
//
//            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL+ Long.valueOf(RandomUtil.randomNumbers(1)), TimeUnit.MINUTES);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            unlock(lockKey);
//
//        }
//        return Result.ok(shop);
//    }

    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("id不能为空");
        }

        String key = CACHE_SHOP_KEY + id;

        // 1. 先删除缓存
        stringRedisTemplate.delete(key);

        // 2. 更新数据库
        updateById(shop);

        // 3. 延迟再删一次缓存（兜底）
        try {
            Thread.sleep(50); // 延迟时间可根据业务和主从延迟调节
            stringRedisTemplate.delete(key);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("延迟双删时被中断", e);
        }

        return Result.ok();
    }


    public Result queryShopBytype(Integer typeId, Integer current, Double x, Double y) {

        if(x==null||y==null){
            Page<Shop> page=query()
                    .eq("type_id",typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        int from=(current-1)*SystemConstants.DEFAULT_PAGE_SIZE;

        int end=current*SystemConstants.DEFAULT_PAGE_SIZE;
        String key=SHOP_GEO_KEY+typeId;

        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        if(results==null){
            return Result.ok(Collections.emptyList());
        }

        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(from>=list.size()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids =new ArrayList<>(list.size());
        Map<String,Distance> distanceMap=new HashMap<>(list.size());
        list.stream().skip(from).forEach(result->{
            String shopIdStr=result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            Distance distance=result.getDistance();
            distanceMap.put(shopIdStr,distance);
        });
        String idStr= StrUtil.join(",",ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);

    }

}
